package com.caigou.modules.info.ui

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseFragment
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.info.R
import com.caigou.modules.info.adapter.InfoItemAdapter
import com.caigou.modules.info.bean.InfoBean
import com.caigou.modules.info.databinding.FragmentInfoTicketBinding
import com.caigou.modules.info.viewmodel.InfoViewModel
import com.caigou.modules.info.viewmodel.LikeViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/09/23
 */
@AndroidEntryPoint
class SingaporeTicketFragment : BaseFragment() {

    private var _binding: FragmentInfoTicketBinding? = null
    private val binding get() = _binding!!

    private val infoViewModel: InfoViewModel by viewModels()
    private val likeViewModel: LikeViewModel by viewModels()

    private var page = 1
    private val limit = 10
    private var totalPage = 0
    private var sort = 1

    private val mAdapter: InfoItemAdapter by lazy {
        InfoItemAdapter(mutableListOf())
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentInfoTicketBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun onBack() {

    }

    override fun initView() {
        binding.infoTicketSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                page = 1
                fetchInfoList()
            }
        }

        mAdapter.loadMoreModule.run {
            setOnLoadMoreListener {
                mAdapter.loadMoreModule.isEnableLoadMore = true
                fetchInfoList()
            }
            isAutoLoadMore = true
            isEnableLoadMoreIfNotFullPage = false
        }

        binding.infoTicketRecyclerView.run {
            layoutManager = GridLayoutManager(requireActivity(), 2)
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(requireActivity()))
        }

        mAdapter.setOnItemClickListener { adapter, view, position ->
            val bean = mAdapter.getItem(position)
            ARouter.getInstance().build(RouterPath.Article.PAGE_ARTICLE)
                .withObject(AppConstants.ARTICLE_ITEM_BEAN, bean)
                .withInt(AppConstants.DATA_ID, bean.dataId)
                .navigation()
        }
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            val item = mAdapter.getItem(position)
            when (view.id) {
                R.id.item_info_iv_like -> {
                    if (AppBackgroundInfo.instance.hasLogin) {
                        if (item.like) {
                            showToast("您已经点过赞了")
                        } else {
                            likeViewModel.setInfoLike(item.dataId, AppBackgroundInfo.instance.userBean!!.userId, item.userInfo.userId)
                        }
                    } else {
                        ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                    }
                }
            }
        }

        binding.infoTicketRgSelector.setOnCheckedChangeListener { group, checkedId ->
            sort = when (group.checkedRadioButtonId) {
                binding.infoTicketBtnComplex.id -> 1
                binding.infoTicketBtnFocus.id -> 5
                binding.infoTicketBtnNicePoint.id -> 3
                binding.infoTicketBtnNewest.id -> 2
                else -> 1
            }
            page = 1
            fetchInfoList()
        }
    }

    override fun lazyLoad() {
        fetchInfoList()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(infoViewModel.articleListLiveData, ::handleGetArticleList)
        observe(likeViewModel.infoLikeLiveData, ::handleSetInfoLike)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun handleGetArticleList(result: Resource<InfoBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.infoTicketSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取资料信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.infoTicketSwipeRefreshLayout.isRefreshing = false
                if (result.data == null) {
                    binding.infoTicketLlEmpty.visibility = View.VISIBLE
                    binding.infoTicketRecyclerView.visibility = View.GONE
                    return
                }

                if (result.data!!.list.isNullOrEmpty()) {
                    binding.infoTicketLlEmpty.visibility = View.VISIBLE
                    binding.infoTicketRecyclerView.visibility = View.GONE
                } else {
                    binding.infoTicketLlEmpty.visibility = View.GONE
                    binding.infoTicketRecyclerView.visibility = View.VISIBLE
                }

                totalPage = result.data!!.totalPage

                if (page == 1) {
                    mAdapter.setList(result.data!!.list)
                } else {
                    mAdapter.addData(result.data!!.list)
                }

                if (result.data!!.pageSize < limit) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    mAdapter.loadMoreModule.loadMoreComplete()
                }

                if (page >= totalPage) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    page++
                }
            }
        }
    }

    private fun handleSetInfoLike(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.infoTicketSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("点赞失败")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.infoTicketSwipeRefreshLayout.isRefreshing = false
                result.data?.apply {
                    showToast(this)
                    page = 1
                    fetchInfoList()
                }
            }
        }
    }


    private fun fetchInfoList() {
        val userId = if (AppBackgroundInfo.instance.hasLogin) {
            AppBackgroundInfo.instance.userBean!!.userId
        } else {
            ""
        }
        infoViewModel.getArticleList(page, limit, userId, sort, 3)
    }
}